package org.mklink.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * 语言工具类，用于管理多语言资源
 */
public class LanguageUtil {
    private static final String BASE_NAME = "i18n/messages";
    private static ResourceBundle resourceBundle;
    private static Locale currentLocale;

    static {
        // 默认使用中文
        setLocale(Locale.SIMPLIFIED_CHINESE);
    }

    /**
     * 设置语言环境
     *
     * @param locale 语言环境
     */
    public static void setLocale(Locale locale) {
        currentLocale = locale;
        // 使用InputStreamReader明确指定UTF-8编码加载资源文件
        try (InputStream inputStream = LanguageUtil.class.getResourceAsStream(
                "/i18n/messages_" + locale.getLanguage() + ".properties");
             InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
            resourceBundle = new PropertyResourceBundle(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前语言环境
     *
     * @return 当前语言环境
     */
    public static Locale getCurrentLocale() {
        return currentLocale;
    }

    /**
     * 根据键获取对应的文本
     *
     * @param key 键
     * @return 对应的文本
     */
    public static String getString(String key) {
        try {
            return resourceBundle.getString(key);
        } catch (Exception e) {
            return '!' + key + '!';
        }
    }

    /**
     * 切换到中文
     */
    public static void switchToChinese() {
        setLocale(Locale.SIMPLIFIED_CHINESE);
    }

    /**
     * 切换到英文
     */
    public static void switchToEnglish() {
        setLocale(Locale.ENGLISH);
    }
}
